
"use strict";


// install click handler
$(function () { 
	
		debug.log(this,  '  install click handler ');
		
	// clear job 
	$("#id_btn_clearjob").click( function() { ;
			em.controller.finishDone();
			em.jobmonitor.force_stop = false;
		});
		
			// start auto attack 
		$("#id_btn_start").click( function() { 
	
			// toggle operation
			em.curOp ^= em.Operation.AUTOHNT;
			
			$("#id_btn_start").toggleClass('control_modeon');
			
			if ( em.curOp & em.Operation.AUTOHNT ) {
				
				debug.log(this,  ' id_btn_start clicked ' , em.curOp.toString(16));
				
				var att_count = $('#att_count').val();
				
				// 항상 moniroe 에 job 을 추가하는 것으로 시작하자.
				em.jobmonitor.addJob( {name: 'StartCstlHnt', fn: em.jobmonitor.startAutoHnt, param: [att_count] });
				// do right now
				em.jobmonitor.doMonitor();
			}
			else {
				debug.log(this,  ' Mode release  ' , em.curOp.toString(16));
			}
			
			return;
			
			
			///= ============= deprecated !!! 
/*
				function myFunc(){
				    return $.Deferred(function( dfd ){
						var start_cstl_index = 0;
						em.controller.doAutoHnt(start_cstl_index, dfd);
						
				        // deferred_obj.resolve( "these", "are", "my", "parameters" );
				        // Call resolve when you are ready to continue, in animation callbacks etc
				    }).promise();
				}
				  
				$.when( myFunc() )
				    .then(function(){
				        console.log( 'done !! in controll box ');
				},
				 function() { 
				 	 console.log( ' fail !! in controll box ');
				 	});
				*/

				});
			


	//  Enhance auto 
	$("#id_btn_enhance").click( function() {

			// clear operation
			em.curOp &= ~em.Operation.ENHANCE ;
			debug.log(this,  'ENHANCE Mode release  ' , em.curOp.toString(16));
		
			if ( ! em.controlbox.enhance_panel) {
				em.controlbox.enhance_panel = new CEnhancePanel();
			} else {
				em.controlbox.enhance_panel.show();		// reshow 
			}
			
		});			
	
	//  buy trade : to support sp30  
	$("#id_btn_buytrade").click( function() {

			em.curOp ^= em.Operation.BUYSP30;
			
			$("#id_btn_buytrade").toggleClass('control_modeon');
			
			if ( em.curOp & em.Operation.BUYSP30) {
				debug.log(this,  ' BUYSP30 clicked ' , em.curOp.toString(16) );
				
				var tem = CDB.SP30.getTemInfo();
				debug.log( this, ' BUY SP30 : Tem info  : ', tem);
				
				em.jobmonitor.addJob( {name: 'BUYSP30', fn: em.jobmonitor.doBuySP30, param: tem });
				em.jobmonitor.doMonitor();
				return;
			}	else {
				debug.log(this,  ' Mode release  ' , em.curOp.toString(16));
			}	
		});			
		
		
	//  H Drin   ... gogo 
	$("#id_btn_hdrink").click( function() {
					// toggle operation
			em.curOp ^= em.Operation.HDRIN;
			
			$("#id_btn_hdrink").toggleClass('control_modeon');
			
			if ( em.curOp & em.Operation.HDRIN ) {
				debug.log(this,  ' id_btn_hdrink clicked ' , em.curOp.toString(16) );
				
				em.jobmonitor.addJob( {name: 'HDRIN', fn: em.jobmonitor.doHDrin, param: [] });
				em.jobmonitor.doMonitor();
				return;
			}	else {
				debug.log(this,  ' Mode release  ' , em.curOp.toString(16));
			}	
		});
		

	// H Fealty 
	$("#id_btn_hfealty").click( function() { ;
			em.controller.doHFealty();
		});





	// world Map search !!
	$("#id_btn_searchWMap").click( function() { 
		
		function cb_complete(DAs) {
			em.util.print_result(DAs);
		};
		
			// 항상 moniroe 에 job 을 추가하는 것으로 시작하자.
		em.jobmonitor.addJob( {name: 'ScanDAsArrWrold', fn: em.jobmonitor.searchDAsArr, param: [] });
		return ; 
/*
		// world 
		em.worldDA = new CWorldDA();
		em.worldDA.startWorldScan(cb_complete);
		
*/
			});



	// go all 6star scan  , 20 �좎룞���좎룞�� 吏ㅵ뜝�숈삕,, 
	$("#id_btn_scanstart").click( function() { 

		var self = this;
		if ( !em.controlbox.scan_panel_init ) {
			// make up scan panel 
			$('#scan_panel')
				.append( '  ArrIdx   :')
				.append( $('<input type=text>').attr('name', 'ArrIdx').attr('value','0')).append( $('<br/>'))
				.append( ' start ---  :')
				.append( $('<input type=text>').attr('name', 'start').attr('value','0')).append( $('<br/>'))
				.append( ' end  ----  :')
				.append( $('<input type=text>').attr('name', 'end').attr('value','99')).append( $('<br/>'))
				.append( $('<button>').text('Start!!!'))
				.append( $('<button>').text('Finish!!!'))
				.show();
				
			em.controlbox.scan_panel_init = true;
			
			// add handler 
			$('#scan_panel button').eq(0).click( function() {
				debug.log( self, 'clicked !!!! Start  #scan_panel button');
				startSacn.call(self);
			});
			// finished 
			$('#scan_panel button').eq(1).click( function() {
				debug.log( self, 'clicked !!!! Finish  #scan_panel button');
				$('#scan_panel').hide();
			});
			return;
		} else {
			$('#scan_panel').show();
		}
		 
		function startSacn() {
			console.log($('#scan_panel').find('input'));
			console.log($('#scan_panel').find('input').eq(0));
			console.log($('#scan_panel :input'));
			
			var arrIdx = $('#scan_panel :input').eq(0).val();
			var startIdx = $('#scan_panel :input').eq(1).val();
			var endIdx = $('#scan_panel :input').eq(2).val();
			
			debug.log(this, 'scan args', arrIdx, startIdx, endIdx);
			if ( !arrIdx || !startIdx || !endIdx) {
				alert('check input value');
				return;
			}
				
				// 항상 moniroe 에 job 을 추가하는 것으로 시작하자.
			em.jobmonitor.addJob( {name: 'scanDAsArr ', fn: em.jobmonitor.scanDAsArr, 
						param: { 'arrIdx' :arrIdx, 'startIdx': startIdx, 'endIdx':endIdx } });
			em.jobmonitor.doMonitor();
			return ; 
		}
		// end 
		
		return;
		});


	// get result !!
	$("#id_btn_getresult").click( function() { 
				
		em.jobmonitor.addJob( {name: 'checkResultAddFav', fn: em.jobmonitor.checkResultAddFav, param: [] });
		 em.jobmonitor.doMonitor();
		 return;
		 
		});
		
		
		
		/*
			PV  ==================================
		*/


// /pvpv   server user seeker 
	$("#id_btn_pvp_uvscan").click( function() { 
		
			debug.log(this,  ' id_btn_pvp_uvscan clicked ');
			
			// 항상 moniroe 에 job 을 추가하는 것으로 시작하자.
			em.jobmonitor.addJob( {name: 'PVP_UserV_Scan', fn: em.jobmonitor.UserVScan_PVP, param: [] });
			// do right now
			em.jobmonitor.doMonitor();
			
			return;

		// $('.castles_container').toggle();
		// $('.cstl_operation').toggle();
	});






	$("#id_btn_pvp_updur").click( function() { 
		
			// toggle operation
			em.curOp ^= em.Operation.DUR_PV;
			
			$("#id_btn_pvp_updur").toggleClass('control_modeon');
			
			if ( em.curOp & em.Operation.DUR_PV ) {
				debug.log(this,  ' id_btn_pvp_updur clicked ' , em.curOp.toString(16) );
				
				em.jobmonitor.addJob( {name: 'PVP_Up_Dur', fn: em.jobmonitor.UpDur_PVP, param: [] });
				em.jobmonitor.doMonitor();
				return;
			}	else {
				debug.log(this,  ' Mode release  ' , em.curOp.toString(16));
			}
	});

	//  avoid others att 
	$("#id_btn_avoid").click( function() { 
		debug.log(this, '...id_btn_avoid btn !!!  ', 'avoid others att  ');
				// toggle operation
			em.curOp ^= em.Operation.AVOID_PV;
			
			$("#id_btn_avoid").toggleClass('control_modeon');
			
			if ( em.curOp & em.Operation.AVOID_PV ) {
				em.jobmonitor.addJob( {name: 'Avoid_PV', fn: em.jobmonitor.checkInterval_PVP, param: [] });
				em.jobmonitor.doMonitor();
			}
			else {
				debug.log(this,  ' Mode release  ' , em.curOp.toString(16));
			}
				
	
		});
	

			
			// sort for pvp 	
	$("#id_btn_getfavs").click( function() { 
		// outer.getfavs();
// 		"x":264,"y":190 :: runner 
		this.myx = 264;
		this.myy = 190;
		var my_x = this.myx;
		var my_y = this.myy;
		this.DAsArr = DAs_Ania_Runner;
		$.each( this.DAsArr, function(_, DaArr) {
			DaArr.sort(function(a,b){
					//  max 처리 .!!!   10 <- 280 - > 260 :  30 !! 
					// 10 - 260  ; 250 ,   280 - 250 : 30  ,  min ( 250, 30)
					//  50 , 80 : 50 -80 : 30,    280 - 30 = 250 ; 
					// 160, 280 : 120 ,  280 - 120 : 160 
					var diff_ay = Math.min( Math.abs(my_y -a.y) ,  280 - Math.abs(my_y - a.y)  );
					var diff_ax = Math.min( Math.abs(my_x -a.x) ,  280 - Math.abs(my_x -a.x)  );

					var diff_by = Math.min( Math.abs(my_y -b.y) ,  280 - Math.abs(my_y - b.y)  );
					var diff_bx = Math.min( Math.abs(my_x -b.x) ,  280 - Math.abs(my_x -b.x)  );
					
					var dis_a = Math.pow(diff_ax,2) + Math.pow( diff_ay, 2) ;
					var dis_b = Math.pow(diff_bx,2) + Math.pow( diff_by, 2) ;
					
					// var dis_a = Math.pow(Math.abs(my_x - a.x ),2) + Math.pow( Math.abs(my_y- a.y), 2) ;
					// var dis_b = Math.pow(Math.abs(my_x - b.x ),2) + Math.pow( Math.abs(my_y- b.y), 2) ;
					return dis_a - dis_b;
				}); 
			});
			
		em.util.print_result(" [ ") ;
		$.each( this.DAsArr, function(_, DaArr) {
			em.util.print_result( '    [') ;
			$.each(DaArr, function(_,da) {
// 				{x:243, y:107, h:5274, n:0 } ,
				em.util.print_result( ' { x:' + da.x + ', y:' + da.y 
						+  (da.h? ', h:' + da.h : '' ) 
						+ (da.n?  ', n:'+ da.n : '' ) +' },') ;
			});
			em.util.print_result( '     ],') ;
		});
		em.util.print_result(" ]; ") ;
					
	});

	
		// test1 b : make Greate sort array 
	$("#id_btn_test3").click( function() { 
			// var All_da_arr = em.data.data_world6star_sort;
				var All_da_arr = data_6star_hn;
				// 占싼덈┛占쏙옙 椰꾧퀡��占쎌뮇�앮에占퐏ort
				//61, 19
				var my_x = 61; var my_y = 19;
				All_da_arr.sort(function(a,b){
					var dis_a = Math.pow(Math.abs(my_x - a.x ),2) + Math.pow( Math.abs(my_y- a.y), 2) ;
					var dis_b = Math.pow(Math.abs(my_x - b.x ),2) + Math.pow( Math.abs(my_y- b.y), 2) ;
					return dis_a - dis_b;
				}); 
				
			// filter... all h 
			var all_h_da_arr =  All_da_arr.filter(function (el) {
				console.log(el );
				if (el.n === 0) 
					return true;
			});
			
			
			var blockidx=0;
			var i;
			for (i=0; i < all_h_da_arr.length; i +=1) {
				// this.block_DA_arr[blockidx++] = All_da_arr[i];
				em.util.print_result(' {x:'+ all_h_da_arr[i].x + ' ,y:' + all_h_da_arr[i].y 
					+ ' , h:' + all_h_da_arr[i].h + ', n:' + all_h_da_arr[i].n + ' } ,');
				// em.util.print_result(' {x:'+ all_h_da_arr[i].x + ' ,y:' + all_h_da_arr[i].y + '} , ');
				
			}
			// console.log(this.block_DA_arr );
			// console.log(this.block_DA_arr.length );	
			em.util.print_result(' >>>>> End make fav da array <<<< ');
				//console.log( CUtil.RandTime	(1000) );
				// em.hntmgr.GetAttDAarr(data_6star_hn);
	});
	
	// test1 b : get DA fav arr 
	$("#id_btn_test2").click( function() { 
		// var All_da_arr = 		data_world6star_sort;
		var All_da_arr = 		data_Greate_6start_allho_hn;
		em.util.print_result(' len :' + All_da_arr.length );
		var blockidx=0;
		for (var i=0; i < All_da_arr.length; i +=5) {
			// this.block_DA_arr[blockidx++] = All_da_arr[i];
			em.util.print_result(' {x:'+ All_da_arr[i].x + ' ,y:' + All_da_arr[i].y + '} ,');
			
		}
		console.log(this.block_DA_arr );
		console.log(this.block_DA_arr.length );	
		em.util.print_result(' >>>>> End make fav da array <<<< ');
		});
	


	
	$("#id_btn_hide").click( this.hideFavslist );

	$("#ctinfotest").click( function () {
				var d = new Date();
				var time_txt = d.getFullYear() + '-' + (d.getMonth() + 1)  + '-' + d.getDate() 
						 + '  ' + d.getHours() + ':' + d.getMinutes() +':' + d.getSeconds();

				$('#start_time').text(time_txt);
				$('#id_ct_deta_1').append('<p>' + time_txt + '</p>');
	} );


	$("#id_btn_test1").click( function() { 
		var result, complete;
		 // tani 55477.
		 em.arenabtl =  new CArenaBtl();
		 em.arenabtl.initialize();
		 	var battle_param = {
				success_cb : succ_battle, 
				error_cb : error_battle,
				notify_cb : noty_battle, 
			};
				em.arenabtl.doArenaBattle(battle_param);

			var count = 0;

			function goNextBattle() {
				em.arenabtl.doArenaBattle(battle_param);
			};
 	
			function succ_battle (code) {
				result = true;
				complete = true;
				console.log('complete !! arena done ' );
				if(code ==0)
					count++;
				em.util.print_result('done  :' + count );
				//  end condition!!
/*
				if ( curIdx > endIdx) {
					em.util.print_result('all done req sacn :' + curIdx );
					return;
				}*/

				
				setTimeout( function() { goNextBattle(); }, CUtil.RandTime(1000));
			};

			function error_battle(code) {
				
				result = false;
				var  errorcode = code;
				complete = true; 
				debug_log("Erro CB is called !!! in test case :" + errorcode + ' curindex : ' + count);
			} ;
			
			function noty_battle(msg) {
			console.log(msg);
			em.util.print_result(msg );
			};
		 
		});
		

	



	// Force Stop Auto  
	$("#id_btn_stop").click( function() { 
			em.util.print_result(' >>>>> Set Force Stop!!! :: fire stop cb  <<<< ');
			
			em.cbs.forcestop.fire();
			// em.hntmgr.SetStop();
		});
		



		
});
// name space
em.controlbox = new function() {
	this.objName = 'CControlBox: ';
	
	// add click handler
	var outer = this;
	
	debug.log(this,  ' start control box ');
	


	// this.setKey = function(key) {
	// var castles = CQuery.setQueryKey(key);
	// };
	
} ();







